package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.MyGoodsActivity;
import com.shwread.android.qysw.activity.TicketOrderDetailActivity;
import com.shwread.android.qysw.adapter.TicketOrderListAdapter;
import com.shwread.android.qysw10000209.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.OrderBean;
import logic.bean.OrderDetailColum;
import logic.util.IRefreshViewListener;
import logic.util.NetworkUtil;
import logic.util.Utils;


/**
 * 待评价页面
 * 
 * @author lexy
 */
public class MyTicketNoCommentView
        extends
        LinearLayout implements
		IRefreshViewListener
{
	
	private MyGoodsActivity mContext;
	private MyListView mContentListView;
	private List<OrderDetailColum>  goodsList          = new ArrayList<OrderDetailColum>(); //单个订单商品详情
	private PullToRefreshScrollView psView;
	private TicketOrderListAdapter orderListAdapter;
	
	private int                     flag               = 0;
	private int                     pagelength         = 1;                                //默认一页显示多少条数据
	private long                    lastOrderCreatTime = 0L;                               //当前页最后一条订单的创建时间
	private int                     currentPageLength  = 1;                                //此次接口请求回来的数据长度                                                                                
	private LoadingView loadingView;

	private ImageView                     ivEmptyIcon;
	private TextView                      tvEmptyConetxt;
	private TextView                      tvEmptyButon;

	private  int PAGENUM = 1;
	private final int LENGTH =10;
	private final String ORDERSTATUS = "30";//"status":0, //int 类型 订单状态 0=未付款 10=已付款(待使用) 20=已使用 30=已过期
	private List<OrderBean.OrderBeanList>   orderList          = new ArrayList<OrderBean.OrderBeanList>();
	private int allPages=0;


	public MyTicketNoCommentView(MyGoodsActivity context) {
		super(context);
		mContext = context;
		initWithContext(context);
	}
	
	@SuppressLint ("NewApi")
    public MyTicketNoCommentView(MyGoodsActivity context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initWithContext(context);
	}
	
	public MyTicketNoCommentView(MyGoodsActivity context, AttributeSet attrs) {
		super(context, attrs);
		initWithContext(context);
	}
	
	private void initWithContext(MyGoodsActivity context) {
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		LinearLayout containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.my_goods_list_lay, null);
		psView = (PullToRefreshScrollView) containerView.findViewById(R.id.my_goods_psview);
		
		View mListView = (View) LayoutInflater.from(context).inflate(R.layout.my_goods_list, null);
		mContentListView = (MyListView) mListView.findViewById(R.id.my_goods_listview);
		
		//		subOrderAdapter = new TicketOrderListAdapter();
		orderListAdapter = new TicketOrderListAdapter(mContext,orderList);
		mContentListView.setAdapter(orderListAdapter);
		psView.addView(mListView);


		View Vempety = LayoutInflater.from(context).inflate(R.layout.my_goods_empty_lay, null);
		ivEmptyIcon = (ImageView) Vempety.findViewById(R.id.my_goods_empty_lay_empey_icon_iv);
		tvEmptyConetxt = (TextView) Vempety.findViewById(R.id.my_goods_empty_lay_conetxt_tv);
		tvEmptyButon = (TextView) Vempety.findViewById(R.id.my_goods_empty_lay_button_tv);
		tvEmptyConetxt.setText("您当前没有已过期的门票信息");
		tvEmptyButon.setVisibility(View.GONE);


		loadingView = (LoadingView) containerView.findViewById(R.id.my_goods_loading_view);
		loadingView.setLoadingAnim(R.drawable.home_progress);
		loadingView.setEmptyView(Vempety);
		//		loadingView.changeLoadingStatus(0);
		
		addView(containerView, lp);
		
		getData(0);
		
		PullToRefreshUtil.initLabel(mContext, psView);
		psView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (psView.isHeaderShown())
				{ //下拉刷新
					refresh();
				}
				else if (psView.isFooterShown())
				{ //上拉加载
					loadMore();
				}
			}
			
		});
		mContentListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				Intent intent = new Intent(mContext,TicketOrderDetailActivity.class);
				intent.putExtra("orderId",orderList.get(i).getId());
				mContext.startActivity(intent);
			}
		});
		
	}
	
	/**
	 * 上拉加载更多
	 */
	private void loadMore() {
		PAGENUM++;
		if (PAGENUM > allPages) {
			PullToRefreshUtil.setLoadLabel(psView, "没有更多数据了");
			psView.onRefreshComplete();
		}
		else {
			getData(2);
		}
	}
	
	/**
	 * 下拉刷新
	 */
	private void refresh() {
		//				Utils.showToast(mContext, "下拉刷新");
		lastOrderCreatTime = 0L;
		PAGENUM=1;
		getData(1);
	}
	
	/**
	 * 关闭加载动画
	 * int flag,int statue
	 * flag 0首次加载，1为下拉刷新，2为上拉加载更多
	 * status 0:加载中，1：加载空白，2 为加载成功 -1：加载失败
	 */
	private void stopLoading(int flag, int status) {
		if (flag == 0)
		{
			loadingView.changeLoadingStatus(status);
		}
		else
		{
			psView.onRefreshComplete();
		}
	}
	
	/**
	 * 获取数据
	 */
	private void getData(int a) {
		this.flag = a;
		if (NetworkUtil.isNetAvailable(mContext))
		{
			loadingView.changeLoadingStatus(0);
			NewActionHelp.qryTicketOrderList(mContext, ORDERSTATUS, PAGENUM, LENGTH, new getDataListener());
		}
		else
		{
			new NoNetDialog(mContext);
		}
		
	}

	@Override
	public void refreshView() {
		getData(0);
	}

	private class getDataListener
	        extends
			ObjectHttpResponseHandler<OrderBean>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			loadingView.setVisibility(View.GONE);
			loadingView.changeLoadingStatus(2);
			Logger.e("错误状态妈--------" + Integer.toString(statusCode));
			Logger.e(throwable);
			currentPageLength = 4;
			if (statusCode < 1000)
			{
				
				Utils.ToastShow(mContext, "网络错误");
			}
			else
			{
				Utils.ToastShow(mContext, "请求出错");
			}
			stopLoading(flag, -1);
			
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, OrderBean obj, String responseString) {
			loadingView.setVisibility(View.GONE);
			loadingView.changeLoadingStatus(2);
			System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
			Logger.i(responseString);
			List<OrderBean.OrderBeanList> object = new ArrayList<>();
			object = obj.getTicketOrderList();
			allPages = obj.getPage().getTotalPage();
			if (object.size() > 0) {
				currentPageLength = object.size();
				if (flag != 2) {
					if (orderList.size() > 0) orderList.clear();
					orderList.addAll(object);
				}
				else {
					orderList.addAll(object);
				}

				orderListAdapter.notifyDataSetChanged();
				changeLoadingStatus(2);
				psView.onRefreshComplete();
			}
			else {
				if(orderList!=null && orderList.size()>0){
					changeLoadingStatus(2);
					psView.onRefreshComplete();
				}else{
					currentPageLength = 0;
					changeLoadingStatus(1);
				}
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<OrderBean>()
			{
			}.getType();
		}
	}
	private void changeLoadingStatus(int status){
		psView.setVisibility(status==2?View.VISIBLE:View.GONE);
		loadingView.setVisibility(status==2?View.GONE:View.VISIBLE);
		if(status!=2) loadingView.changeLoadingStatus(status);
	}
	
}
